import { Result } from '@/domain/Result';
import { DiscipleService } from '@/service/DiscipleService';
import { RecycleBinService } from '@/service/RecycleBinService';
import { RuleService } from '@/service/RuleService';

export class DataService {
  /**
   * 初始化程序
   */
  static initializeApp(): void {
    DiscipleService.initialize();
    RecycleBinService.initialize();
    RuleService.initialize();
  }

  /**
   * 导出本地存储的所有键值为对象
   */
  static exportAllToObject(): Record<string, string> {
    const data: Record<string, string> = {};
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (!key) continue;
      try {
        const value = localStorage.getItem(key);
        if (value !== null) data[key] = value;
      } catch {
        // ignore read errors
      }
    }
    return data;
  }

  /**
   * 将对象中的键值对写入本地存储（全量覆盖写入）
   */
  static importFromObject(obj: unknown): Result {
    if (typeof obj !== 'object' || obj === null) {
      return Result.failure('导入数据格式不正确，应为对象');
    }
    const record = obj as Record<string, unknown>;
    try {
      Object.entries(record).forEach(([key, value]) => {
        // 仅接受字符串值；若是对象/数组，自动转为字符串存储
        if (typeof value === 'string') {
          localStorage.setItem(key, value);
        } else {
          localStorage.setItem(key, JSON.stringify(value));
        }
      });
      DataService.initializeApp();
      return Result.success('导入成功');
    } catch (e) {
      return Result.failure('导入失败');
    }
  }

  /**
   * 重置数据：
   * - 清空 key: chengzheng_recycle_bin
   * - 重置 chengzheng_disciples 中所有弟子的 details 和 scores 字段
   */
  static resetData(): Result {
    try {
      // 清空回收站
      localStorage.removeItem('chengzheng_recycle_bin');

      // 重置弟子数据
      const disciplesKey = 'chengzheng_disciples';
      const raw = localStorage.getItem(disciplesKey);
      if (raw) {
        try {
          const arr = JSON.parse(raw);
          if (Array.isArray(arr)) {
            for (const d of arr) {
              if (d && typeof d === 'object') {
                if ('details' in d) d.details = [];
                if ('scores' in d) d.scores = [];
              }
            }
            localStorage.setItem(disciplesKey, JSON.stringify(arr));
          }
        } catch {
          // 如果 JSON 解析失败，忽略，不写回
        }
      }
      DataService.initializeApp();
      return Result.success('已完成重置');
    } catch {
      return Result.failure('重置失败');
    }
  }
}


